package main

import (
	"api/menus"
	"api/models"
	"api/routers"
	"api/src"
	utils2 "api/utils"
	"api/utils/MyRedis"
	"fmt"
	"strings"
	"time"

	"github.com/beego/beego/v2/core/logs"
	b "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm/utils"
)

func initConfig() {
	appName := b.BConfig.AppName
	b.BConfig.ServerName = "API_" + appName
	b.BConfig.Log.AccessLogs = true
}

func initLogger() error {
	appName := b.BConfig.AppName
	logConfig := fmt.Sprintf(`{"filename": "logger/%s.log"}`, appName)
	err := logs.SetLogger(logs.AdapterFile, logConfig)
	if err != nil {
		logs.Error("设置日志文件发生错误：", err)
	}
	return err
}

func initData(resData []models.Resource) error {
	// 预置系统菜单
	db := models.Db
	result := db.Where("id > 0").Delete(models.Menu{})
	if result.Error != nil {
		logs.Error("删除系统菜单发生错误：", result.Error)
		return result.Error
	}
	menuData := menus.InitMenu()
	result = db.Save(menuData)
	if result.Error != nil {
		logs.Error("预置系统菜单发生错误：", result.Error)
		return result.Error
	}

	// 预置系统资源
	result = db.Where("id > 0").Delete(models.Resource{})
	if result.Error != nil {
		logs.Error("删除系统资源发生错误：", result.Error)
		return result.Error
	}
	if len(resData) > 0 {
		result = db.Save(resData)
		if result.Error != nil {
			logs.Error("预置系统资源发生错误：", result.Error)
			return result.Error
		}
	}

	// 预置系统角色
	menuIds := []string{}
	resIds := []string{}
	for _, item := range menuData {
		id := utils.ToString(item.Id)
		menuIds = append(menuIds, id)
	}
	for _, item := range resData {
		id := utils.ToString(item.Id)
		resIds = append(resIds, id)
	}
	menuStr := strings.Join(menuIds, ",")
	resStr := strings.Join(resIds, ",")
	role := models.Role{1, "超级管理员", menuStr, resStr}
	result = db.Save(role)
	if result.Error != nil {
		logs.Error("预置系统角色发生错误：", result.Error)
		return result.Error
	}

	// 预置系统管理员
	addTime := utils2.MyTime{time.Now()}
	user := models.User{
		Id:       1,
		UserName: "admin",
		Password: "45a7561cc696ddcc", // md5 16位，密码原文：FEVERfever12!@
		Name:     "超级管理员",
		Phone:    "15234579277",
		Email:    "15234579277@139.com",
		Status:   true,
		RoleId:   1,
		Remark:   "",
		AddTime:  addTime,
	}
	result = db.Save(user)
	if result.Error != nil {
		logs.Error("预置系统管理员发生错误：", result.Error)
		return result.Error
	}

	// 删除旧日志
	before := time.Now().AddDate(0, -1, 0) // 一个月以前
	beforeTime := before.Format("2006-01-02")
	result = db.Where("atTime < ?", beforeTime).Delete(models.Logger{})
	if result.Error != nil {
		logs.Error("删除旧日志发生错误：", result.Error)
		return result.Error
	}

	return nil
}

func initStaticDir() error {
	uploadDir, err := b.AppConfig.String("uploadDir")
	if err != nil {
		logs.Error("读取app.conf.uploadDir发生错误：", err)
		return err
	}

	// 建立文件上传文件夹
	appName := b.BConfig.AppName
	uploadPath := uploadDir + "/" + appName
	err = utils2.CreateChildDir(uploadPath)
	if err != nil {
		return err
	}

	// 响应静态文件的网络请求
	b.BConfig.WebConfig.StaticDir["/file"] = uploadPath
	//b.SetStaticPath("/file", uploadPath) // 这样也行，效果是一样的。
	return nil
}

func init() {
	initConfig()

	err := initLogger()
	if err != nil {
		return
	}

	err = MyRedis.InitRedis()
	if err != nil {
		return
	}

	err = models.InitModel()
	if err != nil {
		return
	}

	resourceData := routers.InitRouter()
	err = initData(resourceData)
	if err != nil {
		return
	}

	_ = initStaticDir()
}

func main() {
	b.ErrorController(&src.BaseC{})
	b.Run()
}
